//
//  FindClass.swift
//  FindClass
//
//  Created by tianlong on 2024/9/13.
//

import Foundation

class Find {
    
    // 定义文件搜索函数
    func searchFiles(inDirectory directory: String, forKeyword keyword: String) {
        let fileManager = FileManager.default
        do {
            // 获取目录下所有文件
            let files = try fileManager.contentsOfDirectory(atPath: directory)

            // 遍历文件
            for file in files {
                let filePath = "\(directory)/\(file)"

                // 判断是否为文件夹
                var isDirectory: ObjCBool = false
                if fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory) {
//                    print("遍历文件:filePath ==> \(filePath)")
                    if isDirectory.boolValue {
                        // 递归遍历子文件夹
                        searchFiles(inDirectory: filePath, forKeyword: keyword)
                    } else {
                        // 文件内容搜索
                        if let content = try? String(contentsOfFile: filePath) {
                            if content.contains(keyword) {
                                // 打印包含关键词的文件路径
                                print("找到匹配文件: \(filePath)")
                            }
                        }
                    }
                }
            }
        } catch {
            print("遍历目录失败: \(error.localizedDescription)")
        }
    }
}
